const connect = require('connect');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');

connect()
  .use(morgan('dev'))
  .use(bodyParser())
  .use(methodOverride())
  .use(edit)
  .use(update)
  .listen(3000, function () {
    console.log('http://localhost:3000');
  });

function edit(req, res, next) {
  console.log(req.method);
  console.log(req.originalMethod);
  console.log(req.body);
  if (req.method != 'GET') {
    return next();
  }
  res.setHeader('Content-Type', 'text/html');
  res.write(
    `
<form method="POST">
<input type="hidden" name="_method" value="PUT">
  <input type="text" name="user[name]" value="Tobi">
  <input type="submit" value="Update" >
</form>
      `
  );
  res.end();
}

function update(req, res, next) {
  if (req.method != 'PUT') {
    return next();
  }
  res.end(`Updated name to ${req.body.user.name}`);
}
